//
//  ECUIDelegate.m
//  ECDevelopKit
//
//  Created by LittoCats on 8/13/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "ECSUIDelegate.h"

#import "ECSObjectAttributeWrapper.h"

#import <objc/runtime.h>
#import <objc/message.h>

@interface ECSUIDelegate ()

@end

@implementation ECSUIDelegate

+ (instancetype)defaultInstance
{
    static ECSUIDelegate *delegate = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        delegate = [ECSUIDelegate alloc];
        struct objc_super super;
        super.receiver = delegate;
        super.super_class = [self superclass];
        delegate = objc_msgSendSuper(&super, @selector(init));
    });
    return delegate;
}

- (id)init
{
    return [ECSUIDelegate defaultInstance];
}

+ (void)addOnClickEvent:(id)callback forResponder:(UIView *)responder
{
    ECS_WrapObjectAttribute(responder, callback, ECSSingleClickedKey);
    if ([responder isKindOfClass:[UIControl class]])
        [(UIControl *)responder addTarget:[self defaultInstance] action:@selector(touchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    else
        [responder addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:[self defaultInstance] action:@selector(singleTapGesture:)]];
}

#pragma mark- UITouch event
- (void)touchUpInside:(UIControl *)sender
{
    id callback = ECS_WrappedObjectAttribute(sender, ECSSingleClickedKey);
    [ECSScriptContext callFunction:callback withArguments:sender.ecsAttributes, nil];
}

- (void)singleTapGesture:(UITapGestureRecognizer *)ges
{
    UIView *view = [ges view];
    id callback = ECS_WrappedObjectAttribute(view, ECSSingleClickedKey);
    [ECSScriptContext callFunction:callback withArguments:view.ecsAttributes, nil];
}
@end